const path = require("path");
const PermissionAPIDAO = require(path.join(
  process.cwd(),
  "/dao/PermissionAPIDAO"
));
const DAO = require(path.join(process.cwd(), "/dao/DAO"));
const { values, sortBy } = require("lodash");

module.exports.getMenus = function (userInfo, cb) {
  if (!userInfo) return cb("无权限访问");
  const {rid} = userInfo;
  if (rid == 0) {
    //管理员
    auth(rid, null, cb);
  } else {
    //获取角色权限
    DAO.getByPrimary("RoleModel", rid, function (err, role) {
      if (err || !role) return cb("无权限" + err);
      const rolePermissions = role.ps_ids.split(",");
      let keyRolePermissions = {};
      for (const id of rolePermissions) {
        keyRolePermissions[id] = true;
      }
      auth(rid, keyRolePermissions, cb);
    });
  }
};
// auth(0, {}, ()=>{});
function auth(rid, keyRolePermissions, cb) {
  PermissionAPIDAO.list(function (err, permissions) {
    if (err) return cb("获取权限数据失败" + err);
    const permissionsList = {};
    for (const key in permissions) {
      const permission = permissions[key];
      if (permission.ps_level == 0) {
        if (rid != 0) {
          if (!keyRolePermissions[permission.ps_id]) continue;
        }
        permissionsList[permission.ps_id] = {
          id: permission.ps_id,
          authName: permission.ps_name,
          path: permission.ps_api_path,
          children: null,
          order: permission.ps_api_order,
        };
      }
    }

    for (const key in permissions) {
      const permission = permissions[key];
      if (permission.ps_level == 1) {
        let parent = permissionsList[permission.ps_pid];
        if (rid != 0) {
          if (!keyRolePermissions[permission.ps_id]) continue;
        }
        if (parent) {
          const child = {
            id: permission.ps_id,
            authName: permission.ps_name,
            path: permission.ps_api_path,
            children: null,
            order: permission.ps_api_order,
          };
          permissionsList[permission.ps_pid] = parent = {
            ...parent,
            children: (parent.children && [...parent.children, child]) || [
              child,
            ],
          };
        }
      }
    }
    let list = values(permissionsList);
    list = sortBy(list, "order");
    for (i in list) {
      const subList = list[i];
      if (subList.children)
        subList.children = sortBy(subList.children, "order");
    }
    cb(null, list);
  });
}
